package com.mall.controller.portal;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.mall.common.Const;
import com.mall.common.ResponseCode;
import com.mall.common.ServerResponse;
import com.mall.pojo.MmallUser;
import com.mall.service.IUserService;
import com.mall.util.CookieUtil;
import com.mall.util.JsonUtil;
import com.mall.util.PropertiesUtil;
import com.mall.util.RedisPoolUtil;
/**
 * 
 * 	测试 spring-session 框架 
 *	
 *	步骤: 1.  jar包
 *		 2.  配置web.xml
 *		 3.  配置spring-session.xml
 *
 */

@Controller
@RequestMapping("/user/session/")
public class UserSessioController {
	
	@Autowired
	private IUserService service;
	
	
	@RequestMapping(value="login.do",method=RequestMethod.GET)
	@ResponseBody           //用户登录 
	public ServerResponse<MmallUser> login(String username, String password,HttpSession session,HttpServletResponse response){
		
		//模拟异常产生,然后测试全局异常
		int i = 0;
		int sub = 55/i;
		
		
		ServerResponse<MmallUser> result = service.login(username, password);
		
		if(result.isSuccess()){
		   session.setAttribute(Const.CURRENT_USER,result.getData() );
		}
		
		return result;
	}
	
	@RequestMapping(value="logout.do",method=RequestMethod.GET)
	@ResponseBody           //用户注销登录
	public ServerResponse<String> logout(HttpSession session ,HttpServletRequest request, HttpServletResponse response){
		
		session.removeAttribute(Const.CURRENT_USER);
		
//		String loginToken = CookieUtil.readLoginToken(request);
//		CookieUtil.delLoginToken(request, response);
//		RedisPoolUtil.del(loginToken);
		return ServerResponse.createBySuccess();
	}
	
	
	@RequestMapping(value="getUserInfo.do",method=RequestMethod.GET)
	@ResponseBody			//获取当前登陆的用户的信息
	public ServerResponse<MmallUser> getUserInfo(HttpSession session,HttpServletRequest request){
		
		MmallUser user = (MmallUser)session.getAttribute(Const.CURRENT_USER);
		
//		String loginToken = CookieUtil.readLoginToken(request);

//		if(StringUtils.isEmpty(loginToken)){
//			return ServerResponse.createByErrorMessage("用户未登陆,无法获取用户当前信息");
//		}
		
//		String userStr = RedisPoolUtil.get(loginToken);
//		MmallUser user = JsonUtil.string2Obj(userStr, MmallUser.class);
		
		if(user!=null){
			return ServerResponse.createBySuccess(user);
		}
		return ServerResponse.createByErrorMessage("用户未登陆,无法获取用户当前信息");
	}
	
	
	
}
